/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package di.server.config;

import java.util.Locale;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 *
 * @author Kilian Ito
 */
public class DIViewResolver implements ViewResolver {

    protected ViewResolver page;
    protected ViewResolver mobile;
    protected ViewResolver data;
    protected ViewResolver servlet;
    protected ViewResolver defaultViewResolver;
    
    protected final String pageId = ".html";
    protected final String dataId = ".data";
    protected final String servletId = ".servlet";
    protected final String mobileId = DIInterceptor.mobileId;

    public void setData(ViewResolver data) {
        this.data = data;
    }
    
    public void setDefault(ViewResolver defaultViewResolver) {
        this.defaultViewResolver = defaultViewResolver;
    }

    public void setPage(ViewResolver page) {
        this.page = page;
    }
    
    public void setMobile(ViewResolver mobile) {
        this.mobile = mobile;
    }
    
    public void setServlet(ViewResolver servlet) {
        this.servlet = servlet;
    }
    
    protected boolean isData(String string, Locale locale) {
        return string.indexOf(dataId) >= 0;
    }
    
    protected boolean isPage(String string, Locale locale) {
        return string.indexOf(pageId) >= 0;
    }
    
    protected boolean isServlet(String string, Locale locale) {
        return string.indexOf(servletId) >= 0;
    }
    
    @Override
    public View resolveViewName(String string, Locale locale) throws Exception {
        if (string != null) {
            if (isData(string, locale))
                return data.resolveViewName(string.replace(dataId, ""), locale);
            else if (isPage(string, locale))
                return getBrowerView(string.replace(pageId, ""), locale);
            else if (isServlet(string, locale))
                return servlet.resolveViewName(string.replace(servletId, ""), locale);
        }
        Logger.getLogger(DIViewResolver.class).log(Level.WARN, "Default ResolverView is used");
        return defaultViewResolver.resolveViewName(string, locale);
    }
    
    protected View getBrowerView(String string, Locale locale) throws Exception {
        if (string.indexOf(mobileId) >= 0)
            return mobile.resolveViewName(string.replace(mobileId, ""), locale);
        else
            return page.resolveViewName(string, locale);
    }
}
